// 引入所需的模块和库
//试验阶段，还行不通
const express = require("express");
require("dotenv").config(); // 从.env文件中加载环境变量
const { Configuration, OpenAIApi } = require('openai');


// 配置OpenAI API
const configuration = new Configuration({
  apiKey: process.env.OPEN_AI_KEY, // 使用从环境变量中获取的API密钥
});
const openai = new OpenAIApi(configuration); // 创建OpenAI API实例

// 定义一个POST路由处理程序
exports.findcomplexity = async (req, res) => {
  try {
    const { prompt } = req.body; // 从请求体中获取prompt参数的值

    // 使用OpenAI API创建文本生成请求
    const response = await openai.createCompletion({
      model: "text-davinci-003",
      prompt: `
        ${prompt}

        The time complexity of this function is
        ###
      `,
      max_tokens: 64,
      temperature: 0,
      top_p: 1.0,
      frequency_penalty: 0.0,
      presence_penalty: 0.0,
      stop: ["\n"], // 指定停止标记
    });

    // 将生成的结果作为JSON响应发送回客户端
    return res.status(200).json({
      success: true,
      data: response.data.choices[0].text,
    });
  } catch (error) {
    // 处理错误情况
    return res.status(400).json({
      success: false,
      error: error.response
        ? error.response.data
        : "There was an issue on the server",
    });
  }
};
